package p2p

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"regexp"
)

type Node struct {
	ID      [32]byte
	Name    string
	Address string
	Port    string
}

func GetNodefromfile() map[string]Node {
	nodelist := make(map[string]Node)
	node := &Node{}
	data, err := ioutil.ReadFile(`.\src\p2p\address1.config`)
	if err != nil {
		fmt.Println("Read file error: ", err)
		return nil
	}
	//fmt.Println(string(data))

	//解析正则表达式，如果成功返回解释器
	reg := regexp.MustCompile(`\{[^\}]+\}`)
	if reg == nil {
		fmt.Println("regexp err")
		return nil
	}
	//根据规则提取关键信息
	result1 := reg.FindAllString(string(data), -1)
	for i := 0; i < len(result1); i++ {
		fmt.Println(result1[i])
		err := json.Unmarshal([]byte(result1[i]), node)
		if err != nil {
			return nil
		}
		nodelist[node.Address] = *node
	}
	return nodelist
}

func AddNode(ID [32]byte, Name string, Address string, Port string) error {
	node := Node{ID: ID, Name: Name, Address: Address, Port: Port}
	str, err := json.Marshal(node)
	if err != nil {
		return errors.New("AddNode() json fail")
	}

	// 以追加模式打开文件，当文件不存在时生成文件
	file, err := os.OpenFile(`.\address1.config`, os.O_APPEND|os.O_CREATE, 0666)
	defer file.Close()
	if err != nil {
		return errors.New("AddNode() OpenFile fail")
	}
	// 写入文件
	n, err := file.Write(str)
	// 当 n != len(b) 时，返回错误
	if err == nil && n != len(str) {
		return errors.New("AddNode() Write fail")
	}
	return nil
}
